﻿Imports System.Net.NetworkInformation
Imports System.Text
Imports System.ComponentModel

Public Class MainUI
    Private _Timer As Timers.Timer
    Private _Options As Options
    Private _ListItem As ListViewItem = Nothing
    Private _Messages As StringBuilder

    Public Sub LocalizeUI()
        Me.Text = My.Resources.UI.ApplicationTitle
        Me.uxStatusInfo.Text = String.Format("Welcome to {0}", My.Resources.UI.ApplicationTitle)
    End Sub
    Private Sub NetworkChange_NetworkAvailabilityChanged(ByVal sender As Object, ByVal e As NetworkAvailabilityEventArgs)
        If e.IsAvailable Then
            Me.CheckMail()
        End If
    End Sub
    Private Sub MainUI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.LocalizeUI()
        AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf NetworkChange_NetworkAvailabilityChanged
        If Me.WindowState = FormWindowState.Minimized Then
            Me.Hide()
        End If

        Me._Messages = New StringBuilder

        Me.LoadSettings()
        Me.InitTimer()
        Me.LoadAccounts()
        Me.CheckMail()
    End Sub

    Private Sub InitTimer()
        Me._Timer = New Timers.Timer
        AddHandler Me._Timer.Elapsed, AddressOf _Timer_Elapsed
        Me._Timer.Enabled = True
        Me._Timer.AutoReset = True
        Me._Timer.SynchronizingObject = Me.uxAccountList
        Me._Timer.Interval = Me._Options.TimeInterval * 60000
    End Sub
    Private Sub LoadSettings()
        Dim config As New Configbase(Of Options)
        Me._Options = config.ReadSettings()
    End Sub
    Private Sub _Timer_Elapsed(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
        Me.CheckMail()
    End Sub

    Private Sub MainUI_SizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.SizeChanged
        If Me.WindowState = FormWindowState.Minimized Then
            Me.uxSysIcon.Visible = True
            Me.Hide()
        Else
            Me.uxSysIcon.Visible = False
        End If
    End Sub

    Private Sub uxOptions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxOptions.Click
        Dim options As New OptionsUI
        options.ShowDialog(Me)
    End Sub

    Private Sub uxAccounts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxAccounts.Click
        Dim config As New ConfigUI
        config.ShowDialog(Me)
        Me.LoadAccounts()
    End Sub

    Private Sub uxVisitHome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxVisitHome.Click
        Dim url As String = "http://mailnotify.codeplex.com"
        Process.Start(url)
    End Sub

    Private Sub uxAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxAbout.Click
        Me.ShowAbout()
    End Sub
    Private Sub ShowAbout()
        Dim about As New AboutUI
        about.ShowDialog(Me)
    End Sub

    Private Sub uxExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxExit.Click
        Me.Close()
    End Sub

    Private Sub uxCheckMailNow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxCheckMailNow.Click
        Me.CheckMail()
    End Sub

    Private Sub _Worker_DoWork(ByVal o As Object, ByVal e As DoWorkEventArgs)
        e.Result = Me.CheckInbox(e.Argument.ToString())
    End Sub
    Private Function CheckInbox(ByVal AccountName As String) As Integer
        Dim _coreEngine As Engine
        _coreEngine = New Engine(AccountName)
        Return _coreEngine.NewMails
    End Function
    Private Sub CheckMail()
        Me._Messages.Length = 0 'Resetting the messages
        Dim _mailMessage As String = String.Empty
        Dim _coreEngine As Engine
        Dim _result As Integer
        For Each item As ListViewItem In Me.uxAccountList.Items
            _coreEngine = New Engine(item.Text)
            _result = _coreEngine.NewMails
            If Not _result.Equals(0) Then
                If Integer.Parse(item.Tag.ToString) <> _result Then
                    _mailMessage = String.Format("Account {0} got {1} unread mail(s).{2}", item.Text, _result, Environment.NewLine)
                    _Messages.Append(_mailMessage)
                    item.Tag = _result
                    item.ToolTipText = _mailMessage
                End If
            End If
            _coreEngine = Nothing
        Next
        If _Messages.ToString.Length >= 1 Then
            Me.uxSysIcon.BalloonTipIcon = ToolTipIcon.Info
            Me.uxSysIcon.BalloonTipText = _Messages.ToString
            Me.uxSysIcon.BalloonTipTitle = My.Resources.UI.ApplicationTitle
            Me.uxSysIcon.ShowBalloonTip(1000)
            Me.PlaySound()
        End If
    End Sub
    Private Sub CheckMail(ByVal account As String)
        Me._Messages.Length = 0 'Resetting the messages
        Dim _mailMessage As String = String.Empty
        Dim _coreEngine As Engine
        Dim _result As Integer
        For Each item As ListViewItem In Me.uxAccountList.Items
            If item.Text.Equals(account, StringComparison.CurrentCultureIgnoreCase) Then
                _coreEngine = New Engine(item.Text)
                _result = _coreEngine.NewMails
                If Not _result.Equals(0) Then
                    If Integer.Parse(item.Tag.ToString) <> _result Then
                        _mailMessage = String.Format("Account {0} got {1} unread mail(s).{2}", item.Text, _result, Environment.NewLine)
                        Me._Messages.Append(_mailMessage)
                        item.Tag = _result
                        item.ToolTipText = _mailMessage
                    End If
                End If
                _coreEngine = Nothing
                Exit For
            End If
        Next
        If Me._Messages.ToString.Length >= 1 Then
            Me.uxSysIcon.BalloonTipIcon = ToolTipIcon.Info
            Me.uxSysIcon.BalloonTipText = Me._Messages.ToString
            Me.uxSysIcon.BalloonTipTitle = My.Resources.UI.ApplicationTitle
            Me.uxSysIcon.ShowBalloonTip(1000)
            Me.PlaySound()
        End If
    End Sub
    Private Sub PlaySound()
        If Me._Options.Playsound Then
            If Me._Options.WavFile.Length >= 1 Then
                Dim player As New System.Media.SoundPlayer(Me._Options.WavFile)
                player.Play()
            Else
                System.Media.SystemSounds.Beep.Play()
            End If
        End If
    End Sub
    Private Sub LoadAccounts()
        Me.uxAccountList.Items.Clear()
        Dim _Accounts As List(Of AccountSettings)
        Dim _Item As ListViewItem
        _Accounts = Configbase(Of AccountSettings).GetAccounts()
        For Each item As AccountSettings In _Accounts
            If item.IsEnabled Then
                _Item = New ListViewItem(item.AccountName, 0)
                _Item.Tag = "0"
                Me.uxAccountList.Items.Add(_Item)
            End If
            _Item = Nothing
        Next
    End Sub

    Private Sub MainUI_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If e.CloseReason = CloseReason.WindowsShutDown _
            OrElse e.CloseReason = CloseReason.TaskManagerClosing Then
            e.Cancel = False
        Else
            If MessageBox.Show("Are you sure you want to exit from Mail Notify?", Me.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                Me._Timer.Dispose()
                Me.uxSysIcon.Dispose()
                e.Cancel = False
            Else
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub uxSysExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxSysExit.Click
        Me.Close()
    End Sub

    Private Sub uxCheckMail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxCheckMail.Click
        Me.CheckMail()
    End Sub

    Private Sub uxRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxRestore.Click
        Me.ShowUI()
    End Sub

    Private Sub uxAccountList_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles uxAccountList.MouseDoubleClick
        Dim listItem As ListViewItem = uxAccountList.GetItemAt(e.X, e.Y)
        Dim config As New ConfigUI(listItem.Text)
        config.ShowDialog(Me)
    End Sub
    Private Sub ShowUI()
        Me.Show()
        Me.WindowState = FormWindowState.Normal
        Me.Focus()
    End Sub

    Private Sub uxSysIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles uxSysIcon.MouseDoubleClick
        Me.ShowUI()
    End Sub

    Private Sub uxSysIcon_BalloonTipClicked(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxSysIcon.BalloonTipClicked
        If Me._Options.ApplicationPath.Length >= 1 Then
            Process.Start(Me._Options.ApplicationPath)
        End If
    End Sub

    Private Sub uxListCheckMail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxListCheckMail.Click
        If Me._ListItem IsNot Nothing Then
            Me.WindowState = FormWindowState.Minimized
            Me.CheckMail(Me._ListItem.Text)
        End If
    End Sub

    Private Sub uxAccountList_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles uxAccountList.MouseDown
        Dim listItem As ListViewItem = uxAccountList.GetItemAt(e.X, e.Y)
        If listItem IsNot Nothing Then
            Me._ListItem = listItem
        End If
    End Sub

    Private Sub uxListMenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles uxListMenu.Opening
        Dim enableMenu As Boolean = Me._ListItem IsNot Nothing
        Me.uxListCheckMail.Enabled = enableMenu
        Me.uxEditAccnt.Enabled = enableMenu
        Me.uxRemoveAccnt.Enabled = enableMenu
    End Sub

    Private Sub uxEditAccnt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxEditAccnt.Click
        If Me._ListItem IsNot Nothing Then
            Dim config As New ConfigUI(Me._ListItem.Text)
            config.ShowDialog(Me)
        End If
    End Sub

    Private Sub uxRemoveAccnt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxRemoveAccnt.Click
        If Me._ListItem IsNot Nothing Then
            If MessageBox.Show(String.Format("This will remove this account from Mail Notify.{0}Are you sure you want to remove the account?", Environment.NewLine), Me.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                Dim config As New Configbase(Of AccountSettings)
                config.DeleteAccount(Me._ListItem.Text)
                Me.LoadAccounts()
            End If
        End If
    End Sub

    Private Sub uxAddAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxAddAccount.Click
        Dim config As New ConfigUI
        config.ShowDialog(Me)
    End Sub

    Private Sub uxSysAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxSysAbout.Click
        Me.ShowAbout()
    End Sub

    Private Sub uxImportAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxImportAccount.Click
        If MessageBox.Show(String.Format("Import Account will import an existing account configuration to MailNotify.This operation will over-write any existing account information, with the same account name, if exists, which cannot be undone.{0}{0}Continue?", Environment.NewLine), Me.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Using opendialog As New OpenFileDialog
                With opendialog
                    .AddExtension = True
                    .Filter = "Config Files(*.config)|*.config|All Files(*.*)|*.*"
                    .CheckFileExists = True
                    .DefaultExt = "config"
                    .Multiselect = False
                    .ReadOnlyChecked = False
                    .ShowReadOnly = False
                    .SupportMultiDottedExtensions = True
                    .AutoUpgradeEnabled = False
                    If .ShowDialog = Windows.Forms.DialogResult.OK Then
                        Dim AccntSettings As New AccountSettings
                        AccntSettings = AccntSettings.ReadConfig(.FileName)
                        Dim config As New Configbase(Of AccountSettings)(AccntSettings.AccountName)
                        config.SaveSettings(AccntSettings)
                        Me.LoadAccounts()
                    End If
                End With
            End Using
        End If
    End Sub

    Private Sub MainUI_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.WindowState = FormWindowState.Maximized
        End If
    End Sub
End Class
